My application has two separate dialog windows prior to opening the main application window. I am unable to figure out how to get the second dialog window (the calendar) to open in from of the black python screen (I apologize for my ignorance I don't know the name).
The messagebox contained in "rundate" opens first. If "no" is selected then the app_window opens. It is the app_window that gets hidden
conn = pyodbc.connect('Driver={Microsoft Access Driver (*.mdb, *.accdb)};Dbq='+db)
cur = conn.cursor()
app_window = tk.Tk()
app_window.geometry("1x1+0+0")
app_window.overrideredirect(True)
app_window.transient()
def rundate():
result = tkinter.messagebox.askyesno(title="Rundate", message="back 7 days?")
if result == True:
end = date.today()
start = date.today() - timedelta(7)
daterange = [pd.date_range(start, end)]
for single_date in daterange:
x = single_date.strftime("%m/%d/%Y")
rundate = x
print(rundate)
return rundate
else:
app_window.wm_title("Pick1")
app_window.geometry("250x150+100+100")
app_window.overrideredirect(False)
#app_window.mainloop()
cm = pick1.CalendarFrame(app_window)
cm.grid()
app_window.wait_variable(cm.wait_for_result)
return cm.rundate
rundate = rundate()
print(rundate)
Then a whole bunch of code for queries and whatnot then
After the messagebox is returned "yes" OR the dates are selected from the calendar then the interface gets initiated
# Initiate interface
root = Tk()
master = Frame(root, name='master')
master.pack(fill=BOTH)
root.geometry("800x800+300+100")
root.title('WeeklyReport')
menu_bar = Menu(root)
def exit():
root.destroy()
root.wait_window
I finally figured it out by adding "lift" Thank you!
app_window = tk.Tk()
app_window.geometry("1x1+0+0")
app_window.overrideredirect(True)
app_window.transient()
app_window.lift()
Related
I want a progress bar in popup, that show popup while add extra widgets to the layout, I tried to do it by using tread, creating two tasks one for progress bar another for adding widgets but it is not working as I thought.
I can't share whole code because it is too long.
I need a popup while adding widgets that enough to do my other work.
class FileUploadWindow(Widget):
def choose_file(self):
file = easygui.fileopenbox(default="*.csv")
self.ids.heading.clear_widgets()
self.ids.grid.clear_widgets()
self.ids.index.clear_widgets()
if file is not None:
self.ids.location.text = file
self.file = file.replace('\\', '\\\\')
t1 = threading.Thread(target=self.progress, name='t1')
t2 = threading.Thread(target=self.update_layout, args=[file], name='t2')
t1.start()
t2.start()
t1.join()
t2.join()
def update_layout(self, file):
dataf = pd.read_csv(file)
real = dataf.pop("DEATH_EVENT")
self.ids.heading.add_widget(RecordLabel(text="DEATH_EVENT(p)"))
self.ids.heading.add_widget(RecordLabel(text="Compare"))
for col in list(dataf.columns):
self.ids.heading.add_widget(RecordLabel(text=col))
model = ModelLoading()
predict = model.multipleRecords(dataf[["age",
"creatinine_phosphokinase",
"ejection_fraction",
"serum_creatinine",
"time"]])
for i in range(dataf.shape[0]):
self.ids.index.add_widget(IndexLabel(text=str(i + 1)))
self.ids.grid.add_widget(RecordLabel(text=str(predict[i])))
self.ids.grid.add_widget(RecordLabel(text=str(predict[i] == real[i])))
for j in dataf.columns:
self.ids.grid.add_widget(RecordLabel(text=str(dataf[j][i])))
def progress(self):
progress = MyPopup()
progress.open()
I wonder if it is possible to store in variables the contents from a tree widget row (when it is selected with the mouse) see picture. Basically I want to sync my tree with a database, every time when I insert or delete an element in my tree, my database needs to auto update.
With the insert part it is not a problem , because I have entry widgets, but I don't know how to manage the delete part. Therefore, I wonder if it is possible to do this with some cursor selection function.
I have been trying for a very long time to find a solution for this, I would really appreciate if someone can help me with some hints
Code:
import tkinter
from tkinter import ttk
class cards(tkinter.Frame):
def __init__(self, parent):
tkinter.Frame.__init__(self, parent)
self.parent=parent
self.parent.geometry("800x500")
self.initialize_user_interface()
def initialize_user_interface(self):
self.parent.title("cards")
self.parent.grid_rowconfigure(0,weight=1)
self.parent.grid_columnconfigure(0,weight=1)
self.parent.config(background="lavender")
self.Card_label = tkinter.Label(self.parent, text = "Card type:")
self.Card_entry = tkinter.Entry(self.parent)
self.Card_label.place(x=5,y=5)
self.Card_entry.place(x=70,y=5)
self.SN_label = tkinter.Label(self.parent, text = "SN:")
self.SN_entry = tkinter.Entry(self.parent)
self.SN_label.place(x=5,y=40)
self.SN_entry.place(x=70,y=40)
self.submit_button = tkinter.Button(self.parent, text = "Insert", command = self.insert_data)
self.submit_button.place(x=210,y=15)
self.exit_button = tkinter.Button(self.parent, text = "Exit", command = self.exit)
self.exit_button.place(x=270,y=15)
self.tree = ttk.Treeview( self.parent, columns=('Card Type', 'SN'))
self.tree.heading('#0', text='Nr.')
self.tree.heading('#1', text='Card Type')
self.tree.heading('#2', text='SN')
self.tree.column('#1', stretch=tkinter.YES)
self.tree.column('#2', stretch=tkinter.YES)
self.tree.column('#0', stretch=tkinter.YES)
self.tree.place(x=0,y=100)
self.treeview = self.tree
self.i = 1
def exit(self):
self.master.destroy()
def insert_data(self):
self.treeview.insert('', 'end', text=str(self.i), values=(self.Card_entry.get(), self.SN_entry.get()))
self.i = self.i + 1
def main():
root=tkinter.Tk()
d=cards(root)
root.mainloop()
if __name__=="__main__":
main()
You can use
for item in self.tree.selection():
print(self.tree.item(item, "text"))
print(self.tree.item(item, "values"))
#print(self.tree.item(item))
to see data from all selected rows - you can select more than one row.
You can use it in function assigned to button
or you can use bind() to assign function to mouse click on row.
I am using Python 3.6 and am not able to figure out the logic to select the correct def function when I select a choice from the dropdown box. Below is the code. Please help.
from tkinter import *
root = Tk()
#Combo box
frame = Frame(root)
frame.pack(pady = 30, padx = 10)
tkvar = StringVar(root)
choices = {'gl_Auto','gl_Elec','gl_OP'}
tkvar.set('gl_Auto')
popupMenu = OptionMenu(frame, tkvar, *choices)
popupMenu.pack(side=LEFT,padx=20,pady=20)
Label(frame, text="Select_GL")
def Select_GL(*args): # When I select different gl, it should go to that function
print(tkvar.get())
# link function to change dropdown
tkvar.trace('w', Select_GL)
def keyword_auto():
print(Automotive)
def keyword_elec():
print(Electronics)
def keyword_OP():
print(OP)
root=mainloop()
If you want to go to a function based on the variable value, you simply need to compare the value to an expected string, and call the appropriate function.
def Select_GL(*args):
value = tkvar.get()
if value == "gl_Auto":
keyword_auto()
elif value == 'gl_Elec':
keyword_elec()
else
keyword_OP()
I am building a device that counts how many parts are made off a machine and then turns the machine off at a specific number. I am using an Arduino for all the I/O work and then importing the serial data into Python as variable partCount. I would like to create a simple GUI in tkinter to show the number of parts that have been made and the total number needed. The problem is that I keep getting an error on the label lines that include a variable instead of just a text. I've done a lot of research on it, but I just can't get it for some reason. Any advice would be appreciated.
import serial
import csv
import datetime
import tkinter
#Part Variables
partNumber = "A-33693" #Part Number
stockupTotal = 10
arduinoSerialData = serial.Serial('com3',9600) #Serial Variable
now = datetime.datetime.now()
#GUI
window = tkinter.Tk()
window.title("Troy Screw Products")
titleLabel = tkinter.Label(window, text="Davenport Machine Control")
partNumberLabel = tkinter.Label(window, text="Part #:")
stockUpTotalLabel = tkinter.Label(window, text="Stockup Total:")
partCountLabel = tkinter.Label(window, text="Current Part Count:")
partNumberInfo = tkinter.Label(window, partNumber)
stockUpTotalInfo = tkinter.Label(window, stockupTotal)
partCountInfo = tkinter.Label(window, partCount)
titleLabel.pack()
partNumberLabel.pack()
partNumberInfo.pack()
stockUpTotalLabel.pack()
stockUpTotalInfo.pack()
partCountLabel.pack()
partCountInfo.pack()
window.mainloop()
#Write to CSV File
def writeCsv():
with open("machineRunData.csv", "a") as machineData:
machineDataWriter = csv.writer(machineData)
machineDataWriter.writerow([partNumber, "Stockup Complete",now.strftime("%Y-%m-%d %H:%M")])
machineData.close()
#Serial Import
while (1==1):
if (arduinoSerialData.inWaiting()>0):
partCount = arduinoSerialData.readline()
partCount = int(partCount)
if partCount == 999999:
writeCsv()
print(partCount)
There are several options you can give to a Label widget, as you can see here. You should specify all parameters after the first by name:
partNumberInfo = tkinter.Label(window, text=PartNumber)
To use Python variables in Tkinter you need to special Tk objects, of which there are four: BooleanVar, DoubleVar, IntVar, and StringVar. See this answer for a good example.
So after a ton of research over the last week, I found a solution. The problem was that the program would run the GUI, but not run the code for the serial import until the GUI window was closed. I needed a way to get both the GUI running and updated and get the serial data importing at the same time. I resolved this by creating a thread for both operations. There's probably an easier way to do this, but this what I came up with. The code is below for anyone having a similar problem.
import serial
import time
import threading
from tkinter import *
#Part Variables
partNumber = "A-33693" #Part Number
stockupTotal = 10
partCount = 0
def countingModule():
global partCount
while (1==1):
time.sleep(2)
partCount += 1
print(partCount)
def gui():
global partCount
root = Tk()
pc = IntVar()
pc.set(partCount)
titleLabel = Label(root, text="Machine Control")
partNumberLabel = Label(root, text="Part #:")
stockUpTotalLabel = Label(root, text="Stockup Total:")
partCountLabel = Label(root, text="Current Part Count:")
partNumberInfo = Label(root, text=partNumber)
stockUpTotalInfo = Label(root, text=stockupTotal)
partCountInfo = Label(root, textvariable=pc)
titleLabel.pack()
partNumberLabel.pack()
partNumberInfo.pack()
stockUpTotalLabel.pack()
stockUpTotalInfo.pack()
partCountLabel.pack()
partCountInfo.pack()
def updateCount():
pc.set(partCount)
root.after(1, updateCount)
root.after(1, updateCount)
root.mainloop()
op1 = threading.Thread(target = countingModule)
op2 = threading.Thread(target = gui)
op1.start()
op2.start()
I have a tkinter gui with Python 3.4.2 in which there are various buttons, a user entry field and a text field. Everything works except that I appear to have to click in the Python shell (IDLE) and out of the gui to get fields to update in response to button presses. The updates are immediate when I click on the shell. I have copied this tkintergui from http://ubuntuforums.org/showthread.php?t=1156637 which gives the same problem on my Mac. Immediate update if IDLE shell clicked or very slow update in the GUI
#!/usr/bin/python
from tkinter import *
from tkinter.filedialog import *
class SimpleEdApp:
def __init__(self, parent=Tk()):
self.mainWindow = (parent)
self.mainWindow.title("Simple Editor")
self.mainWindow.resizable(0, 0)
self.make_mnu()
self.make_txt()
def make_txt(self):
self.text = Text(self.mainWindow, width = 80, height = 40, background = 'white')
self.scrollY = Scrollbar(self.mainWindow, orient = VERTICAL, command = self.text.yview, troughcolor = 'white')
self.text["yscrollcommand"] = self.scrollY.set
self.scrollY.pack(side = RIGHT, fill = Y)
self.text.pack(expand = TRUE, fill = BOTH)
def make_mnu(self):
self.menubar = Menu(self.mainWindow)
self.filemenu = Menu(self.menubar, tearoff = 0)
self.filemenu.add_command(label = "Open", command = self.file_open)
self.filemenu.add_command(label = "Save as...", command = self.file_save)
self.filemenu.add_separator()
self.filemenu.add_command(label = "Exit", command = self.mainWindow.destroy)
self.menubar.add_cascade(label = "File", menu = self.filemenu)
self.mainWindow.config(menu = self.menubar)
def file_open(self):
filename =askopenfilename(filetypes=[("pythonfiles","*.py"),("tclfiles","*.tcl"),("allfiles","*")])
f = open(filename, 'r')
data = f.read()
f.close()
self.text.delete(1.0, END)
self.text.insert(1.0, data)
def file_save(self):
filename =asksaveasfilename(filetypes=[("pythonfiles","*.py"),("tclfiles","*.tcl"),("allfiles","*")])
f = open(filename, 'w')
data = self.text.get(1.0, END)
f.write(data)
f.close()
app = SimpleEdApp()
app.mainWindow.mainloop()
Grateful for correct implementation
There is nothing wrong with your code. This looks to be a bug in IDLE.
In the comments you asked how to run the program outside of IDLE. To do that, open up a prompt and type the command python myfile.py, where myfile.py is the name of your python file (assuming "python" is in your PATH).
*note: depending on what is installed in your system, you may need to use python3 rather than python.