【问题标题】:Variable value does not change? (Python)变量值不变? (Python)
【发布时间】:2019-06-07 22:36:43
【问题描述】:

所以我尝试将变量放入标签 x... 以便当变量更改时标签开始移动。

但问题是变量并没有改变它的值,而是当我按下“下一步”按钮时保持在“0”

需要帮助:

import tkinter as tk

from docx import Document

HEIGHT = 500
WIDTH = 600

root = tk.Tk()
canvas = tk.Canvas(root, height=HEIGHT, width=WIDTH)
canvas.pack()

nextt=tk.IntVar()
nextt=0 #setup the nextt variable

label1 = tk.Label(text='example:')
label1.place(x=90+nextt,y=50) #put the variable here to affect position

def next2():
    nextt=300

button2 = tk.Button(text="Next", font=40, command=next2)
button2.place(x=230, y=440) 
#when pressing this button,variable nextt should change to 300, but it doesnt

root.mainloop()

我已经尝试过使用 nextt.set=300 和/或 nextt.get(),所有可能的组合...

【问题讨论】:

  • 您的next2 函数除了分配给局部变量之外什么都不做。
  • next2() 函数内部,nextt 变量是本地变量。它与同名的外部变量没有任何联系。
  • Ok..如何将它与x值中的变量连接起来?

标签: python tkinter


【解决方案1】:

函数next2中的nextt是一个局部变量,您可以尝试将标签放在函数内部:

def next2():
    label1.place(x = 390, y = 50)

如果你想稍后place,那么使用nextt作为全局变量(顺便说一句,这不是一个很好的解决方案):

def next2():
    global nextt
    nextt = 300
# more code
# ...
label1.place(x = 90 + nextt, y = 50)

仅更改nextt 不会自动放置标签,您必须在代码中的其他位置再次执行此操作。

【讨论】:

  • 好的...全局不起作用,并且在定义中放置标签也不起作用...按下按钮使某些东西移动没有其他解决方案吗?
  • @Selfiatus1 你想让它移动一次吗?还是每次按下按钮?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-03-04
  • 2011-11-24
  • 1970-01-01
  • 1970-01-01
  • 2015-04-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多