在一级tk窗口里有个按钮,按钮执行b0,弹出一个新的root0窗口,root0窗口有一个按钮,执行xunhuantupian,但是每次执行的时候,一级tk窗都会
显示在filedialog.askdirectory路径选择框下层,root0窗体上层【也就是一级窗体覆盖了二级窗体】,这是为什么
def b0(): # 图片浏览器
root0 = tkinter.Toplevel()
root0.title('图片浏览器')
root0.geometry("1920x1000-1+0")
def xunhuantupian():
path1 = filedialog.askdirectory(title="请选择图片文件夹:") # 路径选择框获取路径
image_file_list = os.listdir(path1)
image_file_list = [
os.path.join(path1, file)
for file in image_file_list
if file.endswith('.jpg') or file.endswith('jpeg') or file.endswith('png')
] # 获取路径下jpg jpeg png格式图片,写成数组
# 在主窗口中显示第一张图片
current_image = Image.open(image_file_list[0])
if current_image.height > 970: # 对2K以上图片进行等比例缩放处理
aa = current_image.height / 970
current_image = current_image.resize((int(current_image.width / aa), int(current_image.height / aa)))
elif current_image.width > 1920:
aa = current_image.width / 1920
current_image = current_image.resize((int(current_image.width / aa), int(current_image.height / aa)))
else:
current_image = current_image.resize((current_image.width, current_image.height))
current_image_tk = ImageTk.PhotoImage(current_image)
image_label = tkinter.Label(root0, image=current_image_tk)
image_label.place(x=0, y=25)
# 定义切换图片的函数
def change_image(image_index):
global current_image_tk
c1 = Image.open(image_file_list[image_index])
if c1.height > 970:
b1 = c1.height / 970
current_image1 = c1.resize((int(c1.width / b1), int(c1.height / b1)))
elif c1.width > 1920:
aa1 = c1.width / 1920
current_image1 = c1.resize((int(c1.width / aa1), int(c1.height / aa1)))
else:
current_image1 = c1.resize((c1.width, c1.height))
current_image_tk = ImageTk.PhotoImage(current_image1)
image_label.config(image=current_image_tk)
# 设置定时器,在3秒后切换到下一张图片
root.after(3000, lambda: change_image((image_index + 1) % len(image_file_list)))
# 开始循环播放图片
change_image(0)
b0_command22 = tkinter.Button(root0, text="循环", command=xunhuantupian, width=5)
b0_command1.place(x=0, y=0)
参考GPT和自己的思路:这个问题出现的原因是因为在执行xunhuantupian函数时,它在root0窗口中创建了一个新的Label,并把图片放在其中。然而,由于这个Label是在root0窗口中创建的,所以它被视为子Widget,因此在显示FileChooser对话框时会被一级tk窗体遮住。解决这个问题的方法是将Label放在root0窗口的顶层,可以使用pack()
函数或者grid()
函数来实现。同时,需要注意的是,在切换图片时,需要将root0窗口作为参数传递给after()
函数,否则将会出现类似的窗体层问题。
root是啥,是你的一级窗体吗,你为什么要在二级窗体里操作一级窗体
因为askdirectory()等文本对话框方法,都是默认冻结根目录窗口,也就是主窗口,在python的tkinter中,因为绑定tcllib和tklib的缘故,也就是指第一个创建的窗口。
使用参数parent=root0
试一试。