Как вызвать несколько кнопок вместе в Tkinter

Пытаюсь создать окно с 3-мя кнопками. Когда пользователь нажимает одну из кнопок, вызывается назначенная функция. Вот мой код, я перепробовал все из того, что читал в документации, но, похоже, не могу с этим справиться!

Я также добавил функции, вызываемые программой, они работают отлично, просто добавляю их для справки. Кроме того, функция buttons () вызывается только один раз, и это простой вызов без аргументов.

      def buttons():
    root.geometry('1000x1000')

    btncreation = tkinter.Button(root, text='Order by Creation',
                                 command=creation)
    btncreation.pack()

    btnmodified = tkinter.Button(root, text='Order by Last Modified',
                                 command=lastmodified)
    btnmodified.pack()

    btnaccessed = tkinter.Button(root, text='Order by Last Accessed',
                                 command=lastaccessed)
    btnaccessed.pack()


def creation():
    lst.sort(key=os.path.getctime)
    num = 1
    for line in lst:
        dst = newpath + name + str(num) + suffix
        rename(line, dst)
        num += 1


def lastmodified():
    lst.sort(key=os.path.getmtime)
    num = 1
    for line in lst:
        dst = newpath + name + str(num) + suffix
        rename(line, dst)
        num += 1

Функции, вызываемые кнопками:

      def lastaccessed():
    lst.sort(key=os.path.getatime)
    num = 1
    for line in lst:
        dst = newpath + name + str(num) + suffix
        rename(line, dst)
        num += 1

Также, пожалуйста, воздержитесь от форматирования ответов на мой вопрос. Я просто хочу честной помощи, а не 5 комментариев о том, как «лучше отформатировать мой вопрос». Если вам нужна дополнительная информация, я буду рад ее предоставить. Но я не отвечаю на соленые комментарии по форматированию :)

      import os
import tkinter.filedialog
import pathlib
from os import rename
from tkinter import simpledialog
import getpass
import tkinter as tk

root = tkinter.Tk()

# File types list
ftypes = [
    ('Python code files', '*.py'),
    ('Perl code files', '*.pl;*.pm'),
    ('Java code files', '*.java'),
    ('C++ code files', '*.cpp;*.h'),
    ('Text files on mac', '*.rtf'),
    ('Text files', '*.txt'),
    ("PDF files", "*.pdf"),
    ('All files', '*'),
]


# The function renames and relocates selected files depending on the sorting selected
def creation():
    lst.sort(key=os.path.getctime)
    num = 1
    for line in lst:
        dst = newpath + name + str(num) + suffix
        rename(line, dst)
        num += 1


def lastmodified():
    lst.sort(key=os.path.getmtime)
    num = 1
    for line in lst:
        dst = newpath + name + str(num) + suffix
        rename(line, dst)
        num += 1


def lastaccessed():
    lst.sort(key=os.path.getatime)
    num = 1
    for line in lst:
        dst = newpath + name + str(num) + suffix
        rename(line, dst)
        num += 1


def hide(root):
    root.withdraw()


def show(root):
    root.update()
    root.deiconify()


def buttons():
    root.geometry('1000x1000')

    btncreation = tkinter.Button(root, text='Order by Creation',
                                 command=creation)
    btncreation.pack()

    btnmodified = tkinter.Button(root, text='Order by Last Modified',
                                 command=lastmodified)
    btnmodified.pack()

    btnaccessed = tkinter.Button(root, text='Order by Last Accessed',
                                 command=lastaccessed)
    btnaccessed.pack()




hide(root)

# Window to select files to order
filez = tkinter.filedialog.askopenfilenames(title='Select files to rename (must be all of the same type!)')

# List populated with file names
lst = list(filez)

# Saves the extension of the selected files
suffix = pathlib.Path(lst[0]).suffix

# Window to get user input on file naming

# Asks user for file names, while loop won't break if no name is given
USER_INP = simpledialog.askstring(title="File Names",
                                  prompt="Name your files:")

while USER_INP == '':
    USER_INP = simpledialog.askstring(title="File Names",
                                      prompt="Name your files:")

# Gets username for path use
username = getpass.getuser()

name = USER_INP

# Asks user for folder name, while loop won't break if no name is given
USER_INP2 = simpledialog.askstring(title="Folder Name",
                                   prompt="Name your folder:")

while USER_INP2 == '':
    USER_INP2 = simpledialog.askstring(title="Folder Name",
                                       prompt="Name your folder:")

foldername = USER_INP2

# Creates new folder for ordered files, if folder exists, it uses it
newpath = r'/Users/' + username + '/Desktop/' + foldername + '/'
if not os.path.exists(newpath):
    os.makedirs(newpath)

buttons()

root.mainloop()

1 ответ

Решение

Вы можете начать с использования hide(root) но до или после звонка buttons() сказать, show(root), так:

      # Rest of your code
hide(root)
# Rest of your code

show(root)
buttons()
Другие вопросы по тегам