麻烦增加Python 3.4.3 Tkinter中带有标签和按钮的变量

时间:2015-11-02 19:56:53

标签: python python-3.x tkinter increment

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

2 个答案:

答案 0 :(得分:0)

Inkblot有正确的想法。

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

点击"收集灌木"调用force 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.显示灌木的数量由灌木标签对象处理。

答案 1 :(得分:0)

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