所以我开始做一个生存游戏,但是很快就遇到了一个问题。我想做一个按钮,它应该会去收集一定的时间(比如在灌木中),当被击中时,屏幕上显示的灌木数量会增加15。但是每次我尝试这样做的时候,灌木的数量就会从0增加到15,这很好,但这样就不会再高了。下面是我目前的代码:
import tkinter as tk
root = tk.Tk() # have root be the main window
root.geometry("550x300") # size for window
root.title("SURVIVE") # window title
shrubcount = 0
def collectshrub():
global shrubcount
shrubcount += 15
shrub.config(text=str(shrubcount))
def shrub():
shrub = tk.Label(root, text='Shrub: {}'.format(shrubcount),
font=("Times New Roman", 16)).place(x=0, y=0)
def shrubbutton():
shrubbutton = tk.Button(root, command=collectshrub, text="Collect shrub",
font=('Times New Roman', 16)).place(x=0, y=200)
shrub() # call shrub to be shown
root.mainloop() # start the root window任何帮助都会很好!谢谢你得到了这些错误
shrub.config(text=str(shrub count))
AttributeError: 'NoneType' object has no attribute 'config'发布于 2015-11-03 17:21:06
在当前代码中,您在一个函数中定义了灌木,并在只在本地分配它时尝试在另一个函数中使用它。解决方案是完全删除shrub()和shrubbutton()函数,如下所示:
import tkinter as tk
root = tk.Tk()
root.geometry("550x300")
root.title("SURVIVE")
shrubcount = 0
def collectshrub():
global shrubcount
shrubcount += 15
shrub.config(text="Shrub: {" + str(shrubcount) + "}")
if shrubcount >= 30:
print(text="You collected 30 sticks")
craftbutton.pack()
def craftbed():
#Do something
shrub = tk.Label(root, text="Shrub: {" + str(shrubcount) + "}", font=("Times New Roman", 16))
shrub.place(x=0, y=0)
shrubbutton = tk.Button(root, command=collectshrub, text="Collect shrub", font=('Times New Roman', 16))
shrubbutton.place(x=0, y=200)
craftbutton = tk.Button(root, text="Craft bed", comma=craftbed)
root.mainloop() 还在看到问题底部的错误后,变量shrubcount在函数中被命名为shrub count。这样的小事情可以完全改变代码的工作方式。
发布于 2015-11-02 20:57:21
墨迹有正确的想法。
你的灌木函数将灌木的数量设置为0。
点击“收集灌木”调用强制灌木输出灌木丛计数,但在任何时候灌木数量变量都没有更新。
您的代码有一个更干净的版本,您想要做的事情可能如下所示:
import ttk
from Tkinter import *
class Gui(object):
root = Tk()
root.title("Survive")
shrubs = IntVar()
def __init__(self):
frame = ttk.Frame(self.root, padding="3 3 12 12")
frame.grid(column=0, row=0, sticky=(N, W, E, S))
frame.columnconfigure(0, weight=1)
frame.rowconfigure(0, weight=1)
ttk.Label(frame, text="Shrubs:").grid(column=0, row=0, sticky=W)
ttk.Entry(frame, textvariable=self.shrubs, width=80).grid(column=0, row=2, columnspan=4, sticky=W)
ttk.Button(frame, command=self.add_shrubs, text="Get Shrubs").grid(column=6, row=3, sticky=W)
def add_shrubs(self):
your_shrubs = self.shrubs.get()
self.shrubs.set(your_shrubs + 15)
go = Gui()
go.root.mainloop()请注意,所有add_shrub所做的都是增加灌木数15。显示灌木的数量由灌木标签对象处理。
https://stackoverflow.com/questions/33485780
复制相似问题