2017-02-05 36 views
0

Кто-нибудь знает какие-либо альтернативы: корня = Tk()root = Tk(), есть ли альтернативы?

, когда я запустить свою программу, несколько окон выполняются в то же время, просто интересно, есть ли альтернатива, так что они оба DonT открыты одновременно , Второе окно, которое открывается, как только запускается программа, должно запускаться при нажатии кнопки в начальном окне. Я также пробовал использовать: root = Toplevel() , но результаты одинаковы. любые идеи? спасибо

def Search_Inventory(): 
#---First Window---- 
root = Toplevel() 
root.title("Warehouse Inventory Control System") 
root.configure(bg = "black") 

#----Title displayed under the company logo on the first window---- 
Title_Screen = Label(root, 
        text="Warehouse Inventory Control System", 
        fg="grey", 
        bg="black", 
        font="Helevetica 25 bold", 
        pady = "50", 
        padx = "50", 
        ).grid(row=3, column=4) 

#----Interactive Input Boxes for the User---- 

#----Label to Notify what is needed in the entry box---- 

PN_Info_Label = Label(root, 
        text = "Part Number:", 
        fg="white", 
        bg="black", 
        font="Helevetica 15 bold", 
        padx = 50, 
        ).grid(row=14, column=3, rowspan = 2) 

#----Input Box for Part Number 

PN_Display = StringVar() 
Input_PartNumber = Entry(root, 
         textvariable=PN_Display, 
         fg = "blue", 
         font = "Helevtica 25 bold", 
         ).grid(row=14, column=4) 

#----A button that will proceed to the next part of the program---- 

Search_Button = Button(root, 
         text = "Search Inventory", 
         fg = "Blue", 
         bg = "Grey", 
         bd = 2, 
         font="Helevetica 15 bold", 
         command=lambda:Search_Prod(PN_Display.get()), 
         height = 1, 
         width = 15, 
         ).grid(row=16, column=4,pady = 25,padx = 25,) 

#----Information regarding how to enter the part number--- 
Info = Label(root, 
      text="Please Use Capitals to Enter Part Number", 
      fg= "red", 
      bg = "black", 
      font = "helevetica 12 bold", 
      ).grid(row = 15, column = 4) 
#----Adding the company logo to the first window---- 

photo = PhotoImage(file="image.gif") 
photoLabel = Label(image=photo) 
photoLabel.image = photo 
photoLabel.grid(row=1, column=4, pady = 10) 

#----Linking the Help Document---- 

Help_Button = Button(root, 
        text = "Help", 
        command=Help_PDF, 
        fg = "Red", 
        bg = "Black", 
        height = "1", 
        bd = "2", 
        font = "Helevetica 20 bold", 
        width = "4", 
        ).grid(row=0, column=5, pady= 10,padx = 50, sticky = E) 

#----Saying who the program was made by---- 

Credits = Label(root, 
       text = "Created By: Me", 
       fg = "White", 
       bg = "Black", 
       font = "Helevetica 10 underline", 
       ).grid(row = 19, column = 5) 
#To Make Sure that the window doesn't close 
root.mainloop() 

thats подпрограмма, которая предназначена для запуска позже, но сразу же запускается.

root_menu = frame() 
root_menu.title("Warehouse Inventory Control System") 
root_menu.configure(bg = "black") 


photo = PhotoImage(file="logo.gif") 
photoLabel = Label(image=photo) 
photoLabel.image = photo 
photoLabel.grid(row=1, column=3,columnspan = 4, sticky = N) 

Title_Screen = Label(root_menu, 
       text="Welcome to the SsangYong\n Warehouse Inventory          Control System", 
       fg="grey", 
       bg="black", 
       font="Helevetica 25 bold", 
       pady = "50", 
       padx = "50", 
       ).grid(row=2, column=3) 


Search_Inventory = Button(root_menu, 
         command = Search_Inventory(), 
         text = "Search Inventory", 
         fg = "Blue", 
         bg = "Grey", 
         bd = 2, 
         font="Helevetica 12 bold", 
         height = 1, 
         width = 50, 
        ).grid(row=16, column=3,pady = 25,padx = 25,) 

Add_Stock = Button(root_menu, 
      text = "Add New Items", 
      fg = "Blue", 
      bg = "Grey", 
      bd = 2, 
      font="Helevetica 12 bold", 
      height = 1, 
      width = 60, 
      ).grid(row=15, column=3,pady = 25,padx = 25,) 

Print_Report = Button(root_menu, 
      text = "Print Stock Report", 
      fg = "Blue", 
      bg = "Grey", 
      bd = 2, 
      font="Helevetica 12 bold", 
      height = 1, 
      width = 70, 
      ).grid(row=17, column=3,pady = 25,padx = 25,) 


Help_Button = Button(root_menu, 
       text = "Help", 
       command=Help_PDF, 
       fg = "Red", 
       bg = "Black", 
       height = "1", 
       bd = "2", 
       font = "Helevetica 20 bold", 
       width = "4", 
       ).grid(row=1, column=3,rowspan = 2, sticky= NE) 

Credits = Label(root, 
       text = "Created By:mk", 
       fg = "White", 
       bg = "Black", 
       font = "Helevetica 10 underline", 
       ).grid(row = 19, column = 5) 

root_menu.mainloop() 

Это то, что предназначено для всплывающих изначально, но полностью перепутано с другим.

+0

Почему вы используете 'root' вместо' root_menu' в последнем 'Label' во втором файле? – furas

+0

BTW: 'var = Widget(). Grid()' присваивает переменные 'None', потому что' grid() 'возвращает' None' - если вам нужно 'var', то вам нужно сделать в два шага: var = Widget() 'и' var.grid() ' – furas

ответ

0

command= потребности названия функции - обратный вызов - это означает, что без ()

Но вы () в

command = Search_Inventory() 

, и именно поэтому это выполняется при запуске, а не при нажатии кнопки


BTW: tkinter необходимо только один mainloop() - если вы используете два mainloop(), тогда он работает неправильно.


EDIT: Проблема с изображением, потому что вы не установили родителя Label во втором окне

photoLabel = Label(image=photo) 

поэтому используется главное окно по умолчанию

Вам необходимо

photoLabel = Label(root, image=photo) 

EDIT: минимальный рабочий код

from tkinter import * 

def Help_PDF(): 
    pass 

def Search_Inventory(): 

    #--- Second Window ---- 
    root = Toplevel() 

    Title_Screen = Label(root, text="Warehouse Inventory Control System") 
    Title_Screen.grid(row=3, column=4) 

    PN_Info_Label = Label(root, text="Part Number:") 
    PN_Info_Label.grid(row=14, column=3, rowspan=2) 

    PN_Display = StringVar() 

    Input_PartNumber = Entry(root, textvariable=PN_Display) 
    Input_PartNumber.grid(row=14, column=4) 

    Search_Button = Button(root, text="Search Inventory", 
          command=lambda:Search_Prod(PN_Display.get())) 
    Search_Button.grid(row=16, column=4, pady=25, padx=25) 

    Info = Label(root, text="Please Use Capitals to Enter Part Number") 
    Info.grid(row=15, column=4) 

    photo = PhotoImage(file="image.gif") 

    photoLabel = Label(root, image=photo) 
    photoLabel.image = photo 
    photoLabel.grid(row=1, column=4, pady=10) 

    Help_Button = Button(root, text="Help", 
         command=Help_PDF) 
    Help_Button.grid(row=0, column=5, pady=10, padx=50, sticky=E) 

    Credits = Label(root, text="Created By: Me") 
    Credits.grid(row=19, column=5) 


# --- First Window --- 

root_menu = Tk() 

photo = PhotoImage(file="logo.gif") 
photoLabel = Label(root_menu, image=photo) 
photoLabel.image = photo 
photoLabel.grid(row=1, column=3, columnspan=4, sticky=N) 

Title_Screen = Label(root_menu, text="Welcome to the SsangYong\n Warehouse Inventory          Control System",) 
Title_Screen.grid(row=2, column=3) 

Search_Inventory = Button(root_menu, text="Search Inventory", 
         command=Search_Inventory) 
Search_Inventory.grid(row=16, column=3, pady=25, padx=25) 

Add_Stock = Button(root_menu, text="Add New Items") 
Add_Stock.grid(row=15, column=3, pady=25, padx=25) 

Print_Report = Button(root_menu, text="Print Stock Report") 
Print_Report.grid(row=17, column=3, pady=25, padx=25) 

Help_Button = Button(root_menu, text="Help", 
       command=Help_PDF) 
Help_Button.grid(row=1, column=3, rowspan=2, sticky=NE) 

Credits = Label(root_menu, text="Created By:mk") 
Credits.grid(row=19, column=5) 

root_menu.mainloop() 
+0

спасибо, что на самом деле вроде работ, единственное, что сейчас выглядит, что изображения смешиваются –

+0

Я использовал тот же код для изображений –

+0

Опишите его в вопросе – furas

-2

Это возможно. Например: от Tkinter импорта *

from tkinter import * 

def openwinone() : 
    win = Tk() 
    win.title("Window 1") 
    button = Button(text="Spawn Window",command=openwintwo) 
    button.pack() 
    win.mainloop() 

def openwintwo() : 
    wintwo = Tk() 
    wintwo.title("Window 2") 
    label = Label(wintwo,text="Hello, World!") 
    label.pack() 
    wintwo.mainloop() 

openwinone() 

Просто убедитесь, что каждое окно создается в разное время, и имеет другое имя переменной.

Здесь окна и их составляющие элементы создаются при выполнении функции, содержащей их.

+2

Tkinter не должен использовать два 'Tk()' и два 'mainloop()', потому что он создает проблемы с переменными. – furas

+0

Только если вы не справитесь с ними правильно. 'Tk()' определяет новое окно, а 'mainloop()' сообщает окну, что он готов к визуализации. Насколько мне известно, они необходимы для каждого окна. Какие «проблемы» возникают? – Toastrackenigma

+0

В основном есть ошибки с varaibles 'IntVar',' StringVar' и т. Д. – furas

0

Кто-нибудь знает какие-либо альтернативы: root = tk() [так в оригинале]

Там нет альтернативы. Приложение tkinter обязательно должно иметь одно корневое окно.Если вы явно не создаете один (и вы должны), он будет создан для вас при первом создании любого другого виджета.

Второе окно, которое открывается, как только запускается программа, должно запускаться при нажатии кнопки в начальном окне.

Причина в том, что вы говорите, что он немедленно открывается. Посмотрите на этот код:

Search_Inventory = Button(root_menu, 
        command = Search_Inventory(), 

Приведенный выше код идентичен этому:

result = Search_Inventory() 
Search_Inventory = Button(root_menu, command=result) 

Обратите внимание на отсутствие () по команде. Для атрибута command требуется ссылка.

 Смежные вопросы

  • Нет связанных вопросов^_^