Python: Can I open two Tkinter Windows at the same time?

只愿长相守 提交于 2019-12-12 04:08:18

问题


Is it possible to open 2 windows at the same time?

import tkinter as Tk
import random
import math
root = Tk.Tk()
canvas = Tk.Canvas(root)
background_image=Tk.PhotoImage(file="map.png")
canvas.pack(fill=Tk.BOTH, expand=1) # Stretch canvas to root window size.
image = canvas.create_image(0, 0, anchor=Tk.NW, image=background_image)
root.wm_geometry("794x370")
root.title('Map')
root.mainloop()

optimized_root = Tk.Tk()
optimized_canvas = Tk.Canvas(optimized_root)
optimized_root.pack(fill=Tk.BOTH, expand=1)
optimized_image = second.create_image(0, 0, anchor=Tk.NW, image=background_image)
optimized_root.wm_geometry("794x370")
optimized_root.title('Optimized Map')
optimized_root.mainloop()

I'm drawing lines on the first map and then optimizing them to different locations on the second map. That part isn't pictured here, but I want to just open both windows simultaneously and have the random starting points going towards their closest location in the second window. Everything works if I run one at a time, but I have to comment out the other half.


回答1:


Once you have made your first window the other window needs to be a Toplevel

Check out this link to tkinters Toplevel page.

EDIT:

I was playing around with your code to see if I could manage to get 2 windows to open and display an image. Here is what I came up with. It might not be perfect but its a start and should point you in the right direction.

I put the toplevel in as a defined function and then called it as part of the main loop.

NOTE: The mainloop() can only be called once.

from tkinter import *
import random
import math

root = Tk()
canvas = Canvas(root)
background_image=PhotoImage(file="map.png")
canvas.pack(fill=BOTH, expand=1) # Stretch canvas to root window size.
image = canvas.create_image(0, 0, anchor=NW, image=background_image)
root.wm_geometry("794x370")
root.title('Map')

def toplevel():
    top = Toplevel()
    top.title('Optimized Map')
    top.wm_geometry("794x370")
    optimized_canvas = Canvas(top)
    optimized_canvas.pack(fill=BOTH, expand=1)
    optimized_image = optimized_canvas.create_image(0, 0, anchor=NW, image=background_image)

toplevel()

root.mainloop()


来源:https://stackoverflow.com/questions/43552320/python-can-i-open-two-tkinter-windows-at-the-same-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!