我希望能够通过按下startgame()中的按钮来接收设置的名称,并将其存储在getName()中。但我不知道如何从另一个定义中接收变量。我尽我所能,但没有运气?有什么建议吗?
from tkinter import *
root = Tk()
root.wm_title("HangMan")
canvas = Canvas(root, height=400, width=800)
canvas.pack()
def titlescreen():
title = canvas.create_text(400, 100, font=("Times New Roman", 50), tags="title")
canvas.itemconfig(title, text="HANGMAN: THE GAME")
startButton = Button(canvas, text="Start Game", width=10, command=startgame)
canvas.create_window(400, 200, window = startButton)
creditsButton = Button(canvas, text="Credits", width=10, command=displaycredits)
canvas.create_window(400, 250, window = creditsButton)
def startgame():
canvas.delete(ALL)
welcome = canvas.create_text(400,100,font=("Times New Roman",50),text="WELCOME!")
welcome2 = canvas.create_text(400,150,font=("Times New Roman", 30),text="PLEASE ENTER YOUR NAME")
nameEntry = Entry(canvas)
enterName = Button(canvas, text="Enter", width=10,command=getName)
canvas.create_window(350, 200, window = nameEntry)
canvas.create_window(490, 200, window = enterName)
nameEntry.delete(0,END)
nameEntry.insert(0, "Enter Player Name")
name = nameEntry.get()
return name
def getName():
name2 = startgame()
print (name)
return name2
def displaycredits():
canvas.delete(ALL)
created = canvas.create_text(400,100,font=("Times New Roman",50),text="CREATED BY")
credit1 = canvas.create_text(400,150,text="Patrick Tsui & Ricardo Perez")
credit2 = canvas.create_text(400,170,text="Montclair State University Students")
backButton = Button(canvas,text="Back to Title Screen",width=30,command=backtotitle)
canvas.create_window(400, 200, window=backButton)
def backtotitle():
canvas.delete(ALL)
titlescreen()
def drawPole():
canvas.delete(ALL)
a = canvas.create_rectangle(550,50,550,350,fill = "black")
b = canvas.create_rectangle(350,50,550,50,fill = "black")
c = canvas.create_rectangle(350,50,350,90,fill = "black")
titlescreen()
root.mainloop()
答案 0 :(得分:1)
...
canvas.pack()
name = '' # initialize a 'name' variable
def startgame():
def getName(): # define this inside startgame, so we don't need to pass widgets
global name # tell the program that we're referring to the global variable 'name'
name = nameEntry.get() # assign the contents of nameEntry to 'name'
backtotitle() # do something
canvas.delete(ALL)
welcome = canvas.create_text(400,100,font=("Times New Roman", 50),
text="WELCOME!")
welcome2 = canvas.create_text(400,150,font=("Times New Roman", 30),
text="PLEASE ENTER YOUR NAME")
nameEntry = Entry(canvas)
enterName = Button(canvas, text="Enter", width=10,
command=getName) # does not pass widget
canvas.create_window(350, 200, window = nameEntry)
canvas.create_window(490, 200, window = enterName)
nameEntry.delete(0,END)
nameEntry.insert(0, "Enter Player Name")
print(name) # for testing, to see the current name