I am very new on Python and I have a problem.
I try to read my temperature sensor and set the Value in to my Tkinter GUI.
I don't know how to update my label LT with the new value if I update it with my Button B1.
I have tried everything from StringVar to get() and this stuff.
I hope you can help me to find my failure.
Here is my code:
from tkinter import *
import os
Main = Tk()
Main.title("Hauptmenü")
Main.geometry("500x400")
class Fenster():
def Credit():
messagebox.showinfo(title="Credits",message="created by T.N v0.1")
return
def Beenden():
pExit = messagebox.askyesno(title="Beenden",message="Möchten Sie\n wirklich beenden?")
if pExit > 0:
Main.destroy()
return
def auslesen(event):
file = open("/sys/bus/w1/devices/28-041635ad4cff/w1_slave")
inhalt = file.read()
trennwoerter = inhalt.split(" ")
Wert = (trennwoerter[20])
Temp = (Wert[2:4])
file.close()
labelauslesen = Label(Main,text="Aktuelle Temperatur :")
labelauslesen.pack()
LT = Label(Main,text=Inhalt)
LT.pack()
B1 = Button(Main,text="Temperatur auslesen")
B1.pack()
B1.bind("<Button-1>",auslesen)
menubar=Menu(Main)
filemenu = Menu(menubar)
filemenu.add_command(label="Sensoren auslesen")
filemenu.add_command(label="Diagram anzeigen")
filemenu.add_command(label="Credits",command = Credit)
filemenu.add_command(label="Beenden",command = Beenden)
menubar.add_cascade(label="Datei",menu=filemenu)
Main.config(menu=menubar)
mainloop()
A minimal example that you can adapt to your code.
import tkinter as tk
root=tk.Tk()
temp = 10.0
def update_temp():
global temp
temp += 1.3
tlabel['text'] = '%s degrees C' % round(temp, 1)
tlabel = tk.Label(root, text='unknown')
tbutton = tk.Button(root, text='new temp', command=update_temp)
tlabel.pack()
tbutton.pack()
root.mainloop()
Related
variable "code" doesn't change (str) when i check and if i put checkbox() above codeget() there will be no checkbox
how to fix there is code
from tkinter import *
from tkinter import messagebox
from tkinter.ttk import *
#Window
window = Tk()
window.title("Register") #set window title
window.geometry('900x500')
code = 'None'
def codeget():
if (var1.get() == 1) and (var2.get() == 0):
code = 'Python'
elif (var1.get() == 0) and (var2.get() == 1):
code = 'C++'
elif (var1.get() == 0) and (var2.get() == 0):
code = 'None'
else:
code = 'Both'
var1 = IntVar()
var2 = IntVar()
c1 = Checkbutton(window, text='Python',variable=var1, onvalue=1, offvalue=0, command=codeget)
c1.place(x=650,y=120)
c2 = Checkbutton(window, text='C++',variable=var2, onvalue=1, offvalue=0, command=codeget)
c2.place(x=720,y=120)
def luu():
s=open("saveaccount", 'a+')
accountin4 = '\n' + 'Code: ' + code
s.write(accountin4)
message = Button(window,text = "Register", command = luu)
message.place(x = 500, y = 370)
mainloop()
if and else may not be related to my question so you can ignore it, even if I use = to assign " " to the code, the result will still be "None"
codeget() creates local variable code. You have to add global code inside this function to inform function that it has to assign value to global variable code instead of creating local variable code.
Minimal working code with small other changes.
import tkinter as tk # PEP8: `import *` is not preferred
from tkinter import messagebox
import tkinter.ttk as ttk
# --- functions --- # PEP8: all functions before main code
def get_code(): # PEP8: `lower_case_names` for functions and variables
global code # inform function to assign to global variable `code` instead of creating local variable `code`
if var1.get() == 0 and var2.get() == 0:
code = 'None'
elif var1.get() == 1 and var2.get() == 0:
code = 'Python'
elif var1.get() == 0 and var2.get() == 1:
code = 'C++'
else:
code = 'Both'
def register(): # PEP8: readable name
s = open("saveaccount", 'a+')
text = '\n' + 'Code: ' + code
s.write(text)
s.close() # better close file because system may keep data in buffer in RAM and write data when you close file
print(text)
# --- main ---
code = 'None' # it is global variable
window = tk.Tk()
var1 = tk.IntVar()
var2 = tk.IntVar()
c1 = tk.Checkbutton(window, text='Python', variable=var1, onvalue=1, offvalue=0, command=get_code)
c1.pack()
c2 = tk.Checkbutton(window, text='C++', variable=var2, onvalue=1, offvalue=0, command=get_code)
c2.pack()
message = tk.Button(window, text="Register", command=register)
message.pack()
window.mainloop()
PEP 8 -- Style Guide for Python Code
EDIT:
If you want to use more checkbuttons then you could use for-loop to create them, and StringVar to use string onvalue="Python" instead of integers 0/1
import tkinter as tk # PEP8: `import *` is not preferred
from tkinter import messagebox
import tkinter.ttk as ttk
# --- functions --- # PEP8: all functions before main code
def get_code():
global code # inform function to assign to global variable `code` instead of creating local variable `code`
selected = []
for v in string_vars:
if v.get():
selected.append(v.get())
if not selected:
code = 'None'
else:
code = ','.join(selected)
def register():
s = open("saveaccount", 'a+')
text = '\n' + 'Code: ' + code
print(text)
s.write(text)
s.close()
# --- main ---
code = 'None' # it is global variable
window = tk.Tk()
string_vars = []
for item in ['Python', 'C++', 'Java', 'PHP', 'Rust', 'Go']:
v = tk.StringVar(window)
c = tk.Checkbutton(window, text=item, variable=v, onvalue=item, offvalue='', command=get_code)
c.pack()
string_vars.append(v)
message = tk.Button(window, text="Register", command=register)
message.pack()
window.mainloop()
import random
import tkinter as tk
frame = tk.Tk()
frame.title("koeweils baldadige encyptor")
frame.geometry('400x200')
printButton = tk.Button(frame,text = "Print", command = lambda: zandkasteel())
printButton.pack()
freek = tk.Text(frame,height = 5, width = 20)
freek.pack()
input_a = freek.get(1.0, "end-1c")
print(input_a)
fruit = 0
fad = input_a[fruit:fruit+1]
print(fad)
schepje = len(input_a.strip("\n"))
print(schepje)
def zandkasteel():
lbl.config(text = "Ingevulde string: "+input_a)
with open("luchtballon.txt", "w") as chocoladeletter:
for i in range(schepje):
n = random.randint()
print(n)
leuk_woord = ord(fad)*n
print(leuk_woord)
chocoladeletter.write(str(leuk_woord))
chocoladeletter.write(str(n))
chocoladeletter.write('\n')
lbl = tk.Label(frame, text = "")
lbl.pack()
frame.mainloop()
I need to get the string that was entered into the text entry field freek. I have tried to assign that string to input_a, but the string doesn't show up.
Right now, input_a doesn't get anything assigned to it and seems to stay blank. I had the same function working before implementing a GUI, so the problem shouldn't lie with the def zandkasteel.
To be honest I really don't know what to try at this point, if you happen to have any insights, please do share and help out this newbie programmer in need.
Here are some simple modifications to your code that shows how to get the string in the Text widget when it's needed — specifically when the zandkasteel() function gets called in response to the user clicking on the Print button.
import random
import tkinter as tk
frame = tk.Tk()
frame.title("koeweils baldadige encyptor")
frame.geometry('400x200')
printButton = tk.Button(frame, text="Print", command=lambda: zandkasteel())
printButton.pack()
freek = tk.Text(frame, height=5, width=20)
freek.pack()
def zandkasteel():
input_a = freek.get(1.0, "end-1c")
print(f'{input_a=}')
fruit = 0
fad = input_a[fruit:fruit+1]
print(f'{fad=}')
schepje = len(input_a.strip("\n"))
print(f'{schepje=}')
lbl.config(text="Ingevulde string: " + input_a)
with open("luchtballon.txt", "w") as chocoladeletter:
for i in range(schepje):
n = random.randint(1, 3)
print(n)
leuk_woord = ord(fad)*n
print(leuk_woord)
chocoladeletter.write(str(leuk_woord))
chocoladeletter.write(str(n))
chocoladeletter.write('\n')
lbl = tk.Label(frame, text="")
lbl.pack()
frame.mainloop()
I am new to python and trying to build a GUI that takes from date and to date from user and reads the data accordingly from a csv file and display the urine output (calculated in the csvimport fucntion). I also want to plot the graph for a specific time and urine output in that time.
Can anyone help me? My code so far is below and it isn't displaying any GUI. Please can anyone correct the basic errors and help me in running this?
import csv
from tkinter import *
from tkinter.filedialog import askopenfilename
from tkinter.messagebox import showwarning, showinfo
import datetime
#csv_file = csv.reader(open("C:\Users\Lala Rushan\Downloads\ARIF Drop Monitoring Final\ARIF Drop Monitoring Final\DataLog.csv"))
from Tools.scripts.treesync import raw_input
class App(Frame):
def __init__(self, master):
Frame.__init__(self, master)
self.in_file = None
button1 = Button(self, text="Browse for a file", command=self.askfilename)
button2 = Button(self, text="Count the file", command=self.takedate())
button3 = Button(self, text="Exit", command=master.destroy)
button1.grid()
button2.grid()
button3.grid()
self.grid()
def askfilename(self):
in_file = askopenfilename()
if not in_file.endswith(('.csv')):
showwarning('Are you trying to annoy me?', 'How about giving me a CSV file, genius?')
else:
self.in_file=in_file
def CsvImport(csv_file):
dist = 0
for row in csv_file:
_dist = row[0]
try:
_dist = float(_dist)
except ValueError:
_dist = 0
dist += _dist
print ("Urine Volume is: %.2f" % (_dist*0.05))
def takedate(self):
from_raw = raw_input('\nEnter FROM Date (e.g. 2013-11-29) :')
from_date = datetime.date(*map(int, from_raw.split('/')))
print ('From date: = ' + str(from_date))
to_raw = raw_input('\nEnter TO Date (e.g. 2013-11-30) :')
to_date = datetime.date(*map(int, to_raw.split('/')))
in_file = ("H:\DataLog.csv")
in_file= csv.reader(open(in_file,"r"))
for line in in_file:
_dist = line[0]
try:
file_date = datetime.date(*map(int, line[1].split(' ')[1].split('/')))
if from_date <= file_date <= to_date:
self.CsvImport(in_file)
except IndexError:
pass
root = Tk()
root.title("Urine Measurement")
root.geometry("500x500")
app = App(root)
root.mainloop()
You are calling takedate method as soon as you are initializing your class. Removing parentheses(which means, call the method) would solve your issue.
button2 = Button(self, text="Count the file", command=self.takedate())
^^ remove these
Your GUI doesn't show up because takedate method makes your program to wait for user input because of raw_input(..) calls.
You should consider using Entry instead of raw_input() for getting user input.
EDIT: You can put two Entry in your __init__ then use Entry's get method in takedate. Roughly something like below.
def __init__(self, master):
...
...
self.userInputFromRaw = Entry(self)
self.userInputFromRaw.grid()
self.userInputToRaw = Entry(self)
self.userInputToRaw.grid()
def takedate(self):
...
from_raw = self.userInputFromRaw.get()
...
to_raw = self.userInputToRaw.get()
Also, you should add self parameter when defining your method since it is part of that class.
def CsvImport(self, csv_file):
If you not want to pass parameters into self.takedate() remove ()as below:
button2 = Button(self, text="Count the file", command=self.takedate)
or change to
button2 = Button(self, text="Count the file", command=lambda e=Null: self.takedate())
In this case you can pass e parameter to self.takedate(). Pass it to this maner:
command=lambda e=Null: self.takedate(e)
def takedate(self, parameter): pass
I wanted to do something like , if i type something in textbox that command would get executed completely
like this
ie the ~Desktop should be displayed to write next command.
but with my code im getting this also there is an error
as you can see ls command gets executed half in second case
my code is
#!/usr/bin/python
import Tkinter
import subprocess
import tkMessageBox
from Tkinter import *
root = Tk()
class HackBar:
def __init__(self,master):
frame=Frame(master,width = 600,height = 250)
#frame.pack()
def printconsole(event):
print("hello dere ")
def retrieve_input(event):
input = self.Text.get("1.0",'end-1c')
#print(input)
#subprocess.call(input,shell=TRUE)
subprocess.Popen(input)
root.quit()
#root = Tk()
#print p.communicate()
self.button1 = Button(root,text = "Execute")
self.button1.bind("<Button-1>",retrieve_input);
self.button1.grid(row = 0,sticky = E)
self.button2 = Button(root,text = " Quit ")
self.button2.bind("<Button-1>",printconsole);
self.button2.grid(row = 1,sticky = E)
self.Text = Text(root,height =4)
self.Text.grid(row = 0,column = 1,rowspan=2)
menu = Menu(root)
def AboutDialog():
tkMessageBox.showinfo('About','For any issues or suggestion contact rushic24#gmail.com ')
root.config(menu = menu)
submenu1 = Menu(menu)
menu.add_cascade(label="Help",menu=submenu1)
submenu1.add_command(label = "About",command = AboutDialog)
b = HackBar(root)
root.mainloop()
i think i need to use the root.quit() and would again need to start root ,
but it is giving the above error.
Any alternate method would also work.
I am trying to add a reset button but I can't seem to get it to work. I created a main in order to refer back to it when the button is pressed but no luck. Any ideas?
import sys
from tkinter import *
import math
def main():
def closeWin():
myGui.destroy() #Close Window Function
def kiloFunc():
myText = kiloMent.get() #Kilometers to Miles Fuction
convert = 0.62
miles = myText * convert
finalKilo = Label(text = miles,fg='red',justify='center').place(x=200,y=80)
def mileFunc():
myText2 = mileMent.get() #Miles to Kilometers Function
convertTwo = myText2 // 0.62
finalMile = Label(text = convertTwo, fg = 'red',justify='center').place(x=200,y=170)
myGui = Tk()
kiloMent = IntVar()
mileMent = IntVar()
myGui.title("Distance Converter")
myGui.geometry("450x200+500+200")
myLabel = Label(text="Welcome! Please enter your value then choose your option:",fg="blue",justify='center')
myLabel.pack()
kiloEntry = Entry(myGui, textvariable = kiloMent,justify='center').pack()
kilo2milesButton = Button(text = "Kilometers to Miles!", command = kiloFunc).pack()
mileEntry = Entry(myGui, textvariable = mileMent,justify='center').place(x=130,y=105)
miles2kiloButton = Button(text = "Miles to Kilometers!", command = mileFunc).place(x=150,y=135)
reset = Button(text = "Reset Values!", command = main).place(x=10,y=165)
quit = Button(text="Quit", command = closeWin).place(x=385,y=165)
myGui.mainloop()
main()
By calling main() again, you are simply creating another instance of the GUI. What you should do instead is (if I understand correctly), reset the values of the currently existing GUI. You can use the set() method of the GUI objects.
Does
def reset_values():
kiloMent.set(0)
mileMent.set(0)
reset = Button(text="Reset Values!", command=reset_values).place(x=10, y=165)
do the trick?
Looking at your code more thoroughly, however, there are some other problems there, as well. To start with, I would suggest not creating a Label everytime the user tries to convert a value.
This code should work:
from tkinter import *
def main():
def closeWin():
myGui.destroy() # Close Window Function
def kiloFunc():
finalKilo.set(kiloMent.get() * 0.62) # Kilometers to Miles Fuction
def mileFunc():
finalMile.set(mileMent.get() // 0.62) # Miles to Kilometers Function
def clearFunc():
kiloMent.set("0")
mileMent.set("0")
finalKilo.set("")
finalMile.set("")
myGui = Tk()
kiloMent = IntVar()
mileMent = IntVar()
finalKilo = StringVar()
finalMile = StringVar()
myGui.title("Distance Converter")
myGui.geometry("450x200+500+200")
myLabel = Label(text="Welcome! Please enter your value then choose your option:", fg="blue", justify='center')
myLabel.pack()
kiloEntry = Entry(myGui, textvariable=kiloMent, justify='center')
kiloEntry.pack()
kilo2milesButton = Button(text="Kilometers to Miles!", command=kiloFunc)
kilo2milesButton.pack()
mileEntry = Entry(myGui, textvariable=mileMent, justify='center')
mileEntry.place(x=130, y=105)
miles2kiloButton = Button(text="Miles to Kilometers!", command=mileFunc)
miles2kiloButton.place(x=150, y=135)
kiloLabel = Label(textvariable=finalKilo, fg='red', justify='center')
kiloLabel.place(x=200, y=80)
mileLabel = Label(textvariable=finalMile, fg='red', justify='center')
mileLabel.place(x=200, y=170)
reset = Button(text="Reset Values!", command=clearFunc)
reset.place(x=10, y=165)
quit = Button(text="Quit", command=closeWin)
quit.place(x=385, y=165)
myGui.mainloop()
main()
A few notes about your original code besides the ones that Chuck mentioned:
The math and sys imports were unused.
You were setting variables equal to widget.pack() and widget.place(), which are functions that return None.