社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Mike - SMT  »  全部回复
回复总数  3
5 年前
回复了 Mike - SMT 创建的主题 » 点击按钮跳过文件[tkinter+Python3.5]

下面是一个简单的例子,使用PIL加载初始图像,然后使用按钮和函数加载每个下一个图像。

import tkinter as tk
from PIL import ImageTk, Image
import os

path = 'C:/your/file/path/here'

def nextFile():
    # the global is needed to keep track of current index and also keep
    # a reference of the image being displayed so its is not garbage collected.
    global current_ndex, image
    current_ndex += 1
    if current_ndex < len(files):
        img = Image.open('{}/{}'.format(path, files[current_ndex]))
        image = ImageTk.PhotoImage(img)
        # clear the canvas before adding the new image.
        canvas.delete("all")
        canvas.create_image(0, 0, image=image, anchor=tk.CENTER)


my_window = tk.Tk()
my_window.title("File Viewer")
files = os.listdir(path)

current_ndex = 0

button2 = tk.Button(my_window, text="Next", width=50, command=nextFile)
canvas = tk.Canvas(my_window, width=100, height=100)
button2.pack(side=tk.BOTTOM)
canvas.pack()

first_image = files[0]

img = Image.open('{}/{}'.format(path, first_image))
image = ImageTk.PhotoImage(img)
canvas.create_image(0, 0, image=image, anchor=tk.CENTER)
my_window.mainloop()

我想问题是 command=print(self.loadeddata.get("profilename")) 类似于lambda语句的问题(也就是说,我很惊讶您的按钮可以工作,它们应该在 init 之后就再也不工作了,因为您是在创建按钮时调用print,而不是将引用保存到print)。

由于lambda在这样一个循环中工作的性质,您最终只能为所有命令打印循环中的最后一个值。相反,您需要使用lambda语句并在lambda for each循环中定义值,以便准确地记录print语句的正确数据。\

我为此创建了3个测试文件:

test.json :

{"profilename":"test", "profilecolor": "green"}

test2.json :

{"profilename":"test2", "profilecolor": "blue"}

test3.json :

{"profilename":"test3", "profilecolor": "orange"}

示例代码:

import tkinter as tk
import json

class Window(tk.Tk):
    def __init__(self):
        super().__init__()
        self.btn_list = []
        for file in ['test.json', 'test2.json', 'test3.json']:
            with open(file, 'r') as f:
                self.btn_list.append(json.load(f))

        self.create_tags()

    def create_tags(self):
        for item in self.btn_list:
            tk.Button(self, text=item.get("profilename"), background=item.get("profilecolor"),
                      command=lambda x=item.get("profilename"): print(x)).pack(side="top", fill="x")


if __name__ == '__main__':
    Window().mainloop()

结果:

enter image description here

6 年前
回复了 Mike - SMT 创建的主题 » python 3 tkinter checkbutton值

问题是操作顺序。你只是在创造 self.var 在运行其他方法之后。所以当这些方法试图访问 自我价值 他们不能,因为它还没有被创造出来。

移动 self.var=IntVar() 上面 self.create_widgets() .

也就是说你需要改变 IntVar() tk.IntVar() 正如你所展示的那样 import tkinter as tk 因此,所有Tkinter小部件都需要 tk. 前缀。

做这两个更改,代码就可以正常工作了。