为什么我的变量没有相应的翻转?

时间:2017-01-30 06:05:53

标签: python tkinter logic

按钮名为' ft'应该采用值的当前布尔状态,如果它是真的'在'让它变得虚假'关闭'并删除一条红线,或者如果它是假的,则关闭'让它成为真实的'并重新创建红线。出于某种原因,这只有前两次我按下按钮然后它停止工作,我无法弄清楚为什么

   import tkinter
import tkinter.messagebox
from tkinter import *
state="on"
def nothing():
    print ("meh.")
def controller(canvas,redline,test):
    def something(canvas, redline, state):
        if state=="off":
            state="on"
            redline=canvas.create_line(0,100,200,50, fill="red")
            print ("state=off", state)
            return state
        else:
            state="off"
            canvas.delete(redline)
            print ("state=on",state)
            return state
    state=something(canvas, redline, test)
    global state
root=Tk()

canvas = Canvas(root, width=200, height=100)
blackline=canvas.create_line(0,0,200,50)
redline=canvas.create_line(0,100,200,50, fill="red")
greenline=canvas.create_line(0,50,200,50, fill="green")

toolbar=Frame(root, bg="red")
ft=Button(toolbar, text="TEST", command=lambda:controller(canvas,redline,state))
ft.pack(side=LEFT, padx=2, pady=2)
toolbar.pack(side=TOP, fill=X)

canvas.pack()

root.mainloop()

1 个答案:

答案 0 :(得分:1)

你有两个变量redline,一个(本地)内部控制器,第二个(全局)在这个函数之外。再次创建此行时,不会为外部/全局值分配新值。你必须在函数

中使用global redline
import tkinter as tk
import tkinter.messagebox

# --- functions ---

def nothing():
    print ("meh.")

def controller():
    global state
    global redline

    if state:
        canvas.delete(redline)
    else:
        redline = canvas.create_line(0, 100, 200, 50, fill="red")

    state = not state
    print("state:", state)

# --- main ---

state = True

root = tk.Tk()

canvas = tk.Canvas(root, width=200, height=100)
blackline = canvas.create_line(0, 0, 200, 50)
redline = canvas.create_line(0, 100, 200, 50, fill="red")
greenline = canvas.create_line(0, 50, 200, 50, fill="green")

toolbar = tk.Frame(root, bg="red")

ft = tk.Button(toolbar, text="TEST", command=controller)

ft.pack(side='left', padx=2, pady=2)
toolbar.pack(side='top', fill='x')

canvas.pack()

root.mainloop()