在 Python 3.4.3 带有标签和按钮的 Tkinter 中增加变量时出现问题

Trouble incrementing variables in Python 3.4.3 Tkinter with labels and buttons

所以我开始制作一款生存游戏,但是 运行 很快就遇到了问题。我想做一个按钮,它应该会去收集一定的时间,(如在灌木丛中),当点击时,屏幕上显示的灌木数量将增加 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'

Inkblot 有正确的想法。

您的灌木函数将灌木的数量设置为 0。

单击 "Collect Shrub" 调用会强制 shrub 输出 shrubcount 但 shrubcount 变量永远不会更新。

您的代码的更简洁版本,可以执行您想要的操作,可能如下所示:

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 所做的只是将 shrubcount 增加 15。显示灌木的数量由灌木标签对象处理。

在您当前的代码中,您在一个函数中定义了 shrub 并尝试在仅在本地分配它时在另一个函数中使用它。解决方案是像这样完全删除 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 。像这样的小事情可以完全改变您的代码的工作方式。