Python Tkinter访问函数内部的变量,用于在函数外使用。

问题描述 投票:0回答:1

我正在构建一个gui,从用户那里获取excel文件和日历输入。我想在调用它们的函数之外使用文件路径和日历日期。我怎样才能做到这一点?我试过在这些函数中使用全局变量,但没有用。

import tkinter as tk
from tkinter import *, filedialog
from tkcalendar import Calendar, DateEntry
import pandas as pd
from datetime import datetime
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By

root = Tk()

def browse():
    root.filename = filedialog.askopenfile(initialdir="/downloads", title="Select a file",
                                           filetypes=((".xlsx files", "*.xlsx"), ("all files", "*.*")))

def date_picker():
    top = tk.Toplevel(root)
    cal = Calendar(top, font="Arial 14", selectmode='day', locale='en_US', disabledforeground='red',
                   cursor="hand1", date_pattern='MM/dd/yyyy')
    cal.pack(fill="both", expand=True)

    def quit():
        top.destroy()

    tk.Button(top, text="ok", command=quit).pack()

def exit():
root.destroy()

okButton = Button(root, text="OK", command=exit)
stuLabel = Label(root, text="Date")
calLabel = Label(root, text="Date to Start Summing")
calButton = Button(root, text="Date", command=date_picker)
fileButton = Button(root, text="File", command=browse)
fileLabel = Label(root, text="Select a File")
exitButton = Button(root, text="Exit")
stuLabel.grid(row=0, column=0)
calLabel.grid(row=1, column=0)
fileLabel.grid(row=2, column=0)
calButton.grid(row=1, column=1)
fileButton.grid(row=2, column=1)
okButton.grid(row=3, column=0)
exitButton.grid(row=3, column=1)

root.mainloop()

browser = webdriver.Chrome()
browser.get('a website')
type(browser)

delay = 20

df = pd.read_excel(filename, Sheet_name=0, header=None) # Here I want to access the chosen file

sum_start = browser.find_element_by_name('date') 
    sum_start.click()
    # clear date
    sum_start.clear()
    sum_start.send_keys(str(date) + Keys.ENTER) # Here I want to access the date selected by the user
python tkinter
1个回答
0
投票

有区别 filedialog 调用。

askopenfile() 以只读模式返回打开的文件对象。askopenfilename() 返回选定的文件名。

这可能是你在使用 globals 时遇到困难的原因。如果文件名是一个字符串,它可以正常工作(对我来说...)

from tkinter import *
from tkinter import filedialog

root = Tk()

def browse():
    global filename
    filename = filedialog.askopenfilename(
        initialdir="/downloads", title="Select a file",
        filetypes=((".xlsx files", "*.xlsx"), ("all files", "*.*")))

browseButton = Button(root, text='Browse', command=browse)
browseButton.pack(padx=40, pady=20)

root.mainloop()

print(filename)     # Here I want to access the chosen file
© www.soinside.com 2019 - 2024. All rights reserved.