how i can with just with the checked entry widgets - python

Hi,
i just wanna ask you guys, if is there any way to work with just checked chexboxes
here it my code :
from tkinter import *
window1 =Tk()
window1.geometry("400x400")
window1.resizable(False,False)
#---------------------------------------------
def test1():
if entry1['state'] == 'normal':
entry1['state'] = 'disabled'
else:
entry1['state'] = 'normal'
entry1 =Entry()
entry1.pack()
cb1 = Checkbutton(command=test1)
cb1.select()
cb1.pack()
#---------------------------------------------
def test2():
if entry2['state'] == 'normal':
entry2['state'] = 'disabled'
else:
entry2['state'] = 'normal'
entry2 =Entry()
entry2.pack()
cb2 = Checkbutton(command=test2)
cb2.select()
cb2.pack()
#---------------------------------------------
def test3():
if entry3['state'] == 'normal':
entry3['state'] = 'disabled'
else:
entry3['state'] = 'normal'
entry3 =Entry()
entry3.pack()
cb3 = Checkbutton(command=test3)
cb3.select()
cb3.pack()
#---------------------------------------------
def test4():
if entry4['state'] == 'normal':
entry4['state'] = 'disabled'
else:
entry2['state'] = 'normal'
entry4 =Entry()
entry4.pack()
cb4 = Checkbutton(command=test4)
cb4.select()
cb4.pack()
#---------------------------------------------
def message():
b = float (entry1.get())
c = float ( entry2.get())
d = float ( entry3.get())
e = float ( entry4.get())
label1 = Label(window1, text="1) here is what you wrote ma boy :"+ str(b))
label1.place(x=60,y=200)
label2 = Label(window1, text="2) here is what you wrote ma boy :"+ str(c))
label2.place(x=60,y=230)
label3 = Label(window1, text="3) here is what you wrote ma boy :"+ str(d))
label3.place(x=60,y=260)
label4 = Label(window1, text="4) here is what you wrote ma boy :"+ str(e))
label4.place(x=60,y=290)
button1 = Button(window1,text="Click", command= message, width=8)
button1.place(x=20,y=200)
window1.mainloop()
here is what i want :
i want to check the checkbox 2 and 4 for example and enter values and i want the code to execute just the second and the forth message. if i check the the first,second and the forth checkboxes,and enter values, i want the code to execute just the first, the second and the forth message. and so one . i wish u unerstand what i'm trying to say.
thank you in advance,
and i'm sorry for my bad English
if there is a tutorial that can help me in this , plz just share it.

The checkbuttons command is executed every time you click on it. The checkbutton takes additional options like variable a tkinter variable that is set to onvalue and offvalue depending on an internal state. Check your variable in the function and alter the entry as you desire.
update
You could check the variable even in a different function like your message function.
import tkinter as tk
def message():
if var.get():
print(entry.get())
entry.delete('0',tk.END)
def test():
if var.get():#check variable
entry['state'] = 'normal'
else:
entry['state'] = 'disabled'
root = tk.Tk()
entry = tk.Entry()
var = tk.BooleanVar(value=False)#tkinter variable
checkbutton = tk.Checkbutton(command=test,
onvalue=True,
offvalue=False,
variable=var)
button = tk.Button(text='Print',command=message)
checkbutton.invoke()
##checkbutton.invoke()
button.pack(side=tk.BOTTOM,fill=tk.BOTH)
entry.pack(side=tk.RIGHT)
checkbutton.pack(side=tk.LEFT)
root.mainloop()

Related

Enable or disable buttons after all widget entries are complete in tkinter

I am making a simple GUI in tkinter to test entry validations. Most of this code appears to work, except getting the calculate button to show up enabled in green as soon as the entries are complete.
What I'm trying to achieve is that once all the entries are complete and radiobuttons are selected, the calculate button is then enabled and is visibly "available". Once the calculate button has been used the submit button is then enabled. When both buttons have been used the form resets.
I need to have both buttons in the application. Button1 (calculate) should perform some calculations AND do error checking on entry widgets. Button 2 needs to submit the data from the form to a file, but only if the validation checks were correct and the calculation has been made. I'm fairly new to python, and despite a lot of researching I cannot quite get it to work.
I think the answer in this post might help me, but I'm not completely sure how to incorporate it How to disable the following button in Tkinter? .
I tried using .bind or .trace respectively with the variables for each widget, because I'd seen some examples using that method, but I got errors. I've tried various ways of enabling or disabling the buttons using .config, but essentially as a new coder I'm just having trouble even finding out what method or tool I should be using, or how to write the functions to operate as I need them.
import tkinter as tk
from tkinter import *
from tkinter import messagebox
from pathlib import Path
ws = Tk()
ws.title('Validation test')
ws.geometry('400x300')
ws.config(bg='#04B2D9')
#attempts to set the button to enabled once radiobutton is chosen
def enable_calc():
global a
a = var.get()
if a == 1:
butt1.config(state=NORMAL, bg="lightgreen")
elif a == 2:
butt1.config(state=NORMAL, bg="lightgreen")
#calculation associated with butt1, called in validation function
def calculate(*args):
global b
choice = var.get()
if choice == 1:
a = 10
if choice == 2:
a = 15
b = a * 4
calc.config(text=f"the amount is {b} ")
butt2.config(state=NORMAL, bg="lightgreen")
butt1.config(state=DISABLED, bg="lightgrey")
#attempts to validate the name entry
def validation(*args):
global select, name_check
select = var.get()
name_check = name_var.get()
msg = ''
butt2.config(state=DISABLED, bg="lightgrey")
#attempts to call the calculation if radiobutton selected
if select ==1:
calculate()
elif select ==2:
calculate()
else:
messagebox.showwarning("Please enter all fields ")
butt2.config(state=DISABLED, bg="lightgrey")
butt1.config(state=DISABLED, bg="lightgrey")
#checks name entry for input
if len(name_check) == 0:
msg = 'name can\'t be empty'
else:
try:
if any(ch.isdigit() for ch in name_check):
msg = 'Name can\'t contain numbers'
elif len(name_check) <= 2:
msg = 'name is too short.'
elif len(name_check) > 100:
msg = 'name is too long.'
else:
msg = 'Success!'
butt2.config(state=NORMAL, bg="lightgreen")
except Exception as ep:
messagebox.showerror('error', ep)
messagebox.showinfo('message', msg)
#writes the file (should be only if calculate was successful) and clears the widgets
def submit():
file_sent = ""
try:
filepath = Path("C:/Temp/text_example.txt")
filepath.parent.mkdir(parents=True, exist_ok=True)
with filepath.open("a", encoding ="utf-8") as f:
f.write(f"\n Name : {name_check}")
f.close()
file_sent = f" Success! {name_check}, your application has been submitted"
except Exception as ep:
messagebox.showerror('error', ep)
messagebox.showinfo('message', file_sent)
name_tf.delete(0,END)
butt2.config(state=DISABLED, bg="lightgrey")
var.set(0)
#plotting components
frame = tk.LabelFrame(ws, padx=10,pady=10)
frame.pack(pady=20)
first_name = tk.Label( frame, text='Enter Name')
first_name.grid(row=0, column=1)
calc = tk.Label(frame)
calc.grid(row=5, column=1)
name_var = StringVar()
name_tf = tk.Entry(frame, textvariable=name_var,
font = ('sans-sherif', 14))
name_tf.grid(row=1, column=1)
var = IntVar()
var.set(0)
var.trace('w', enable_calc)
opt1 = tk.Radiobutton(frame,pady=10,padx=20,
variable=var, value=1).grid(row=2, column=1)
opt2 = tk.Radiobutton(frame, pady=10,padx=20,
variable=var, value=2).grid(row=2, column=2)
butt1 = tk.Button(frame,text='Calculate', pady=10,padx=20)
butt1.grid(row=3, columnspan=2)
butt1.bind('<Button-1>', validation)
butt2 = tk.Button(frame, text='Submit', pady=10,
padx=25,command=submit)
butt2.grid(row=4, columnspan=2)
ws.mainloop()

Comparing user input in Tkinter

I have a issue with tkinter. I want to use Entry to take info from the user and then
compare it to a string if the result is true I want it to print a Label on the screen
and if false I want it to print something else. For some reason the .get does not
show for me, and I can't find a way to compare the user input in. The Entery to a simple
string that I saved as a variable.
from tkinter import *
window = Tk()
window.geometry("800x600")
window.title("Sara's chocolate balls")
def Button_Click():
test1 = "hey"
if entry1 == test1:
test2.pack()
else:test3.pack()
entry1 = Entry(window, width=30).pack()
Button1 = Button(window, text="Button", command=Button_Click).pack()
test2 = Label(window, text="Good")
test3 = Label(window, text="Bad")
window.mainloop()
So I found a solution:
entry1 = Entry(window,textvariable=var, width=30).pack()
var = StringVar()
user_input = var.get()
It works like that.

Tkinter - How to limit the space used by a Text?

I'm trying to create a factorial calculator GUI.
The program works fine, but the problem I'm having is that when there are too many numbers coming in from the output, the screen automatically increases in width. I've tried using tk.Text to create a limit to the size of the textbox and so the text continues to the next row when the columns are filled.
But when I had to input text in to the tk.Text it didn't work since the variable I used is being processed in the function that gets called when the button is pressed. I have tried googling this problem but I couldn't find anything, I did find some people explaining how to use variables that get created/processed inside of a function, but that didn't work so I think I have done something wrong in my code.
Note: I am using lambda to call my function (not sure if this is important or not).
TLDR: Text gets too long when too much information is outputted. tk.Text didn't work for me since I couldn't figure out how to use the variable that is created/processed inside of a function that is only called when the button is pressed.
Here is my entire code: https://pastebin.com/1MkdRjVE
Code for my function:
def start_calc():
output_array = ["placehold"]
start_text.set("Loading...")
i = 1
global e1
global e2
output_array.clear()
string = e1.get()
string2 = e2.get()
integr = int(string)
integr2 = int(string2)
if string == "":
error_message.set("Please enter correct numbers.")
elif string2 == "":
error_message.set("Please enter correct numbers.")
else:
while integr2 >= i:
calc = integr ** i
calcstr = (str(calc))
output_array.append(calcstr)
i += 1
start_text.set("Start!")
output_array_str = (', '.join(output_array))
output_msg.set("Output: " + output_array_str)
print(output_array_str) #This is just so I know if it's working or not in the terminal
Code for my output:
output_msg = tk.StringVar()
output_text = tk.Label(root, textvariable=output_msg, font="Raleway")
output_msg.set("Output: ")
output_text.grid(columnspan=3, column=0, row=14)
I think this is what you are looking for:
#Imports
import tkinter as tk
#Variables
root = tk.Tk()
#Tkinter GUI setup basic
canvas = tk.Canvas(root, width= 400, height=400)
canvas.grid(columnspan=3, rowspan=120)
#Title
text = tk.Label(root, text="Calculating factorials", font="Raleway")
text.grid(column=1, row=1)
#Function
def start_calc():
output_array = ["", ""]
start_text.set("Loading...")
i = 1
global e1
global e2
output_array.clear()
string = e1.get()
string2 = e2.get()
integr = int(string)
integr2 = int(string2)
if string == "":
error_message.set("Please enter correct numbers.")
elif string2 == "":
error_message.set("Please enter correct numbers.")
else:
while integr2 >= i:
calc = integr ** i
calcstr = (str(calc))
output_array.append(calcstr)
i += 1
start_text.set("Start!")
output_array_str = (', '.join(output_array))
# Change the output
output_text.config(state="normal")
# delete last output:
output_text.delete("0.0", "end")
# insert new output:
output_text.insert("end", output_array_str)
output_text.config(state="disabled")
print(output_array_str) #This is just so I know if it's working or not in the terminal
#input
tk.Label(root, text="Number :").grid(row=10)
tk.Label(root, text="Factorial :").grid(row=11)
e1 = tk.Entry(root)
e2 = tk.Entry(root)
e1.grid(row=10, column=1)
e2.grid(row=11, column=1)
#Error message if the input is invalid
error_message = tk.StringVar()
error_text = tk.Label(root, textvariable=error_message, font="Raleway")
error_message.set(" ")
error_text.grid(column=1, row=12)
#Startbutton
start_text = tk.StringVar()
start_btn = tk.Button(root, textvariable=start_text, command=start_calc, font="Raleway", bg="#20bebe", fg="white", height=2, width=15)
start_text.set("Start!")
start_btn.grid(column=1, row=13, pady=10)
#output
output_text = tk.Text(root, height=1, width=20, wrap="none", font="Raleway")
output_text.insert("end", "Output")
output_text.config(state="disabled")
output_text.grid(columnspan=3, column=0, row=14, sticky="news")
#Adding a scrollbar
scrollbar = tk.Scrollbar(root, orient="horizontal", command=output_text.xview)
scrollbar.grid(columnspan=3, column=0, row=15, sticky="news")
output_text.config(xscrollcommand=scrollbar.set)
#disclaimer message
disclaimer_text = tk.Label(root, text="Disclaimer: The factorials will be printed from 1 to the number you entered.")
disclaimer_text.grid(columnspan=3, column=0, row=110)
root.mainloop()
I used a <tkinter.Text> widget with wrap="none", height=1 and width=20 to make the output box. I disabled the entry so that the user can't change the results but can still copy it.

python gui AND/OR programm

I am using python GUI. So here's the deal https://learn.digilentinc.com/Documents/Digital/BT02_03_Basic_Logic_Truth_Table/AndOrTruthTable.svg
It should be like this. For example, if the user writes 1 in entry a and 0 in entry b and he chooses "and" radio button in label c should appear 0.
I tried something but it didn't work. Can anyone help me?
This is my code that doesn't work:
from tkinter import *
root = Tk()
a = Label(root,text = "enter number a")
b = Label(root,text = "enter number b")
c = Label(root)
a.grid(row=0, sticky=E)
b.grid(row=1, sticky=E)
c.grid(row=3, sticky=E)
entry_a = Entry(root)
entry_b = Entry(root)
entry_a.grid(row=0, column=1)
entry_b.grid(row=1,column=1)
v = IntVar()
def ifvisnull(event):
if entry_a == 1 and entry_b == 1:
print(1)
else:
print(0)
def ifvisone(event):
if entry_a == 0 and entry_b == 0:
print(0)
else:
print(1)
button1 = Radiobutton(root, text="and", variable = v, value = True, command = ifvisnull())
button2 = Radiobutton(root, text="or", variable = v, value = False, command = ifvisone())
button1.grid(row=2,column=0)
button2.grid(row=2,column=1)
root.mainloop()
my name is Vikas.
So there are a few problems i your code.
in all radiobutton , in the command option you had put parenthesis-()
infront of the command which you have to remove
ex: command=ifvisnull
then in all functions you have given event argument which you need not to
until and unless you are binding the widget to an event.
So,just remove event argument
Lastly , in each function to get the value of entry box you need to use
entry.get() function/method.
Directly writing entry_a will not give you the value
And also this method will return in str type .

TKInter Python checkbutton state

I am trying to do some work on a text file if certain checkbuttons are checked.
"Populate CheckBoxes"
Label(master, text="Pick at least one index:").grid(row=4, column=1)
Checkbutton(master, text="Short",variable=var1).place(x=5,y=60)
Checkbutton(master, text="Standard",variable=var2).place(x=60,y=60)
Checkbutton(master, text="Long",variable=var3).place(x=130,y=60)
Calling
print("Short: %d,\nStandard: %d,\nLong: %d" % (var1.get(), var2.get(),
var3.get()))
prints out 0 or 1 for each variable but when I am trying to use that value to do something it does'nt seem to call the code.
if var2.get(): <--- does this mean if = 1?
Do something
In below example var.get()'s value is printed in command prompt if it's False and updates the lbl['text'] if it's True:
import tkinter
root = tkinter.Tk()
lbl = tkinter.Label(root)
lbl.pack()
var = tkinter.BooleanVar()
def update_lbl():
global var
if var.get():
lbl['text'] = str(var.get())
else:
print(var.get())
tkinter.Checkbutton(root, variable=var, command=update_lbl).pack()
root.mainloop()
But below code never prints as "0" and "1" are both True:
import tkinter
root = tkinter.Tk()
lbl = tkinter.Label(root)
lbl.pack()
var = tkinter.StringVar()
def update_lbl():
global var
if var.get():
lbl['text'] = str(var.get())
else:
print(var.get())
tkinter.Checkbutton(root, variable=var, command=update_lbl).pack()
root.mainloop()

Categories

Resources