Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.5k views
in Technique[技术] by (71.8m points)

python 3.x - How to call a function in my canvas.create_text

Hi I'm trying to create a gui application using tkinter, pandas and Python 3. Basically I want it to pull a random park name from the csv when the user pushes the button to get park. Then I want the park name to be displayed in the park_text = canvas.create_text area so that it will populate in this canvas for the user to see. How can I go about accomplishing this? Any pointers would be much appreciated.

from tkinter import *
import pandas
import random
import csv

BACKGROUND_COLOR = "#006600"
BUTTON_COLOR = "#6699ff"


# User clicks Get Park button which generates a random park name from the original park csv
def new_park():
    with open("stl_parks_list.csv") as f:
      park = f.readlines()
      chosen_park = random.choice(park)
      print(chosen_park)    


# User confirms that they want to visit this park. The park name will then be moved to a new csv of visited parks and removed from the original parks list.
def confirm_park():
    pass


# Push the "Skip" button to skip the park and get a different suggestion. Park names remain on the parks list until they are confirmed.
def skip_park():
    pass


# --- UI Setup ---
window = Tk()
window.title("St. Louis Parks at Random")
window.config(padx=20, pady=20, bg=BACKGROUND_COLOR)

canvas = Canvas(width=300, height=100, bg="white")
park_text = canvas.create_text(
            150, 
            50, 
            text="TEST", 
            fill=BACKGROUND_COLOR,
            font=("Ariel", 20, "italic")
            )
canvas.grid(row=1, column=0, columnspan=2, pady=20, sticky="NESW")

# --- Label ---
website_label = Label(text="St. Louis Parks at Random", fg="white", bg=BACKGROUND_COLOR)
website_label.grid(column=1, row=0, columnspan=2)

# --- Buttons ---
get_park_button = Button(text="GET PARK", width=20, bg=BUTTON_COLOR, font=("bold"), command=new_park)
get_park_button.grid(column=0, row=2, columnspan=2, sticky='', pady=20) 

confirm_button = Button(text="CONFIRM", width=10, bg=BUTTON_COLOR, font=("bold"), command=confirm_park)
confirm_button.grid(column=0, row=3)

skip_button = Button(text="SKIP", width=10, bg=BUTTON_COLOR, font=("bold"), command=skip_park)
skip_button.grid(column=1, row=3)



window.mainloop()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use canvas.itemconfig to change the text value of a canvas item:

def new_park():
    with open("stl_parks_list.csv") as f:
      park = f.readlines()
      chosen_park = random.choice(park)
      canvas.itemconfig(park_text, text = chosen_park)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...