Get random text variable from tkinter button - python - python

The title might be a little confusing, so i will describe my question more.
I making a little program that will assist me with studying Chinese, just for myself. This will aid me with coding and in same time with studying.
I encounter a problem with getting the text variable from my button, without function the code work like wanted. But when trying to get random text that shown on the button it cause me a problem, because text doesn't come. All i need it, when button is pressed function check if input is the same as character and give correct/incorrect notice.
I little new to coding, so it can be simple matter, but still appreciate any help.
The code:
#========== Imports ===========#
from tkinter import *
from tkinter import messagebox
import random
#========== Parameters ==========#
CN = Tk()
CN.title("Chinese Test")
CNW = ["爱","八","爸爸","杯子","北京","本","不客气","不","菜","茶","吃","出租车","打电话",
"大","的","点","电脑","电视","电影","东西","都","读","对不起","多","多少","儿子",
"二","饭店","飞机","分钟","高兴","个","工作","汉语","好","号","喝","和","很","后面","回","会","几","家","叫","今天"]
Cword = ""
Cent = StringVar()
def butPress():
global Cword
if (B0.text==Cword): #wrong way to get text
messageText = "Correct"
else:
messageText = "Incorrect"
CNEntry = Entry(CN,textvariable = Cent).grid(row = 0, column = 1, columnspan = 8)
B0 = Button(CN, text = random.choice(CNW),command = lambda:butPress,bd = 3, width = 5, height = 3).grid(row = 6, column = 4, padx = 10, pady = 10)
#========== Pack ==========#
CN.mainloop( )

There's a few things.
First of all, command = lambda:butPress doesn't work. Use command = butPress. You should only use a lambda when you need to pass parameters (e.g. command = lambda:butPress(parameter)), which you don't.
Then there's B0.text. Because you do
B0 = Button(...).grid(...)
B0 is None, because that is what grid() returns. Change it to
B0 = Button(...)
B0.grid(...)
This way B0 is a Button object. To get the current text of it you can't use B0.text, you have to use B0['text'].
You then compare the text to Cword, which is '' and never changes. If you want to compare it to the entered text in the Entry use CNEntry.get() (after again putting grid on a separate line).

Related

Moving text from a button to another using python tkinter

def move(sp, t):
if sp == "eightA":
sps = eightA
if t == "sixA":
st = sixA
if st == " ":
# target is empty
sps["text"] = " "
st["text"] = str(sps["text"])
Hello Everyone, Im trying to make this function to "move" text from a tkinter button to another, lets say sp is what i want to move, and t is the target so i want to move text
from the button eightA to sixA, also note that i want to be able to use this function on any 2 buttons, Its hard to explain, but please help if you can, the code above is one i tried out of alot other which didnt work,
Thanks
Procedure
Store the text on first button in a variable
Configure first button to have no text
Configure second button to have text stored in variable
Example
btn1 = tk.Button(text="Hello")
btn2 = tk.Button(text="Not Hello")
# store text on btn1 in a variable
txt = btn1['text']
# configure btn1 to have no text
btn1.config(text="")
# configure btn2 to have text stored in variable
btn2.config(text=txt)
So your function would look like
def move(btn1, btn2):
txt = btn1['text']
btn1.config(text=" ")
btn2.config(text=txt)

Button command doesn't updates my Label textvariable

I have this very easy program which I want to display one random line from a file each time I click on the Button.
Problem is a new line is display at startup of the program, but nothing happens when I click the button, can someone explain me why ?
from random import randrange
from tkinter import *
def entree():
n=randrange(251)
fs = open('lexique','r')
liste = fs.readlines()
return liste[n]
fen = Tk()
fen.title("lexique anglais politique")
defi = StringVar()
defi.set(entree())
lab = Label(fen, textvariable=defi).pack()
Button(fen, text='Beste Bat', command=entree).pack()
fen.mainloop()
As stated in one of the comments (by #matszwecja), your entree() function doesn't really do anything appart from returning a value.
Nothing in your code updates the actual label. Try something like this :
from random import randrange
from tkinter import *
def entree():
n=randrange(251)
fs = open('lexique','r')
liste = fs.readlines()
return liste[n]
def update_label():
lab.config(text=entree())
fen = Tk()
fen.title("lexique anglais politique")
lab = Label(fen, text=entree())
lab.pack()
Button(fen, text='Beste Bat', command=update_label).pack()
fen.mainloop()
In this example, the entree() function is used to go get a line from your file, and the update_label() function is used to actually update the label.
Also, if you want to be able to update a label, you'll have to pack it after assigning it to a variable.
On a side note, it could be worth noting that hardcoding values that could change in the future is generally considered bad practice. In that regard, I think coding the entree() function this way might be a better idea :
def entree():
fs = open('lexique','r')
liste = fs.readlines()
n=randrange(len(liste))
return liste[n]
This way, if you ever add or remove lines to your "lexique" file, you will not have to change the code.

ValueError: Either a title or a pageid must be specified

The code displayed below is giving me a ValueError, explaining I need a title or pagid specified. I have checked the code over and over and do not see a problem. Please let me know if you have any idea what I am doing wrong.
This code is meant to give me information about most key words I enter. If I want Jeff Bezos, information will be printed to the console.
# Imports
import wikipedia
from tkinter import *
import time
# Code
def Application():
# Definitions
def Research():
# Defines Entry
Result = wikipedia.summary(Term)
print(Result)
# Window Specifications
root = Tk()
root.geometry('900x700')
root.title('Wikipedia Research')
# Window Contents
Title = Label(root, text = 'Wikipedia Research Tool', font = ('Arial', 25)).place(y = 10, x = 250)
Directions = Label(root, text = 'Enter a Term Below', font = ('Arial, 15')).place(y = 210, x = 345)
Term = Entry(root, font = ('Arial, 15')).place(y = 250, x = 325)
Run = Button(root, font = ('Arial, 15'), text = 'Go', command = Research).place(y = 300, x = 415)
# Mainloop
root.mainloop()
# Run Application
Application()
You're passing Term to wikipedia.summary(). The error is coming from when summary() creates a page (code). This error happens when there is no valid title or page ID being passed to the page (code). This is happening in your case because you're passing Term straight to summary(), without first converting it to a string. Additionally, Term is a NoneType object, because you're actually setting it to the result of place(). You have to store Term when you create the Entry(), and then apply the place operation to it, in order to be able to keep a reference to it (see here for why):
Term = Entry(root, font = ('Arial, 15'))
Term.place(y = 250, x = 325)
Then, you can get the text value via:
Result = wikipedia.summary(Term.get())

.set in function is not being found in other function so it's creating an error tkinter python

I'm trying to create a GUI, in the nav menu you can click a cascade option to open another window where you can click roll to generate a set of numbers. It comes up with error. I think it's because the function is called from another function I just don't know how to get that function to call it/ if there is any other ways to fix this. I've tried global functions and looking it up but haven't found anything other than using classes so far, which I don't know how to do.
line 147, in totalRolls
txtresultsOut.set(totalRollResults)
NameError: name 'txtresultsOut' is not defined
Here is the code that is relevant to it. I've called the function to skip having to input all the other code for the main gui window.
def rollSix():
s = 0
numbers = [0,0,0,0]
for i in range(1,5):
numbers[s] = randrange(1,7)
s += 1
numbers.remove(min(numbers))
Result = sum(numbers)
totalRollResults.append(Result)
def totalRolls():
rollOne()
rollTwo()
rollThree()
rollFour()
rollFive()
rollSix()
txtresultsOut.set(totalRollResults)
def rollw():
rollWindow = tix.Tk()
rollWindow.title("Dice Rolls")
diceLabel = Label(rollWindow, text = "Click Roll for your Stats")
diceLabel.grid(row = 0, column = 0)
rollBtn = Button(rollWindow, text = "Roll Stats", command = totalRolls)
rollBtn.grid(row = 1, column = 0)
txtresultsOut = StringVar()
resultsOut = Entry(rollWindow, state = "readonly", textvariable = txtresultsOut)
resultsOut.grid(row = 2, column = 0)
rollw()
first of all I would NOT recommend using StringVar(). You can use the .get() method of Entry to obtain the value inside the same. Try this way and make a global declaration of the Entry whose values you want to get in other functions.
EDIT------------
#you can use the following code to make your entry active to be edited.
entry.configure(state='normal')
# insert new values after deleting old ones (down below)
entry.delete(0,END)
entry.insert(0, text_should_be_here)
# and finally make its state readonly to not let the user mess with the entry
entry.configure(state='readonly')

Python Tkinter/GUI Not Updating/Working Correctly

I'm wondering if anyone can give me a quick simple fix for my issue.
I'm trying to make a program (as a gcse mock) that will obtain the position of words in a sentence.
I have the sentence bit working great in the text however I want to go above and beyond to get the highest possible marks so I'm creating it again with a gui!
So far I have the following code and it's not working correctly, it's not updating the 'sentence' variable and I'm looking for a simple way around fixing this Instead of updating. I get some random number which I'm not sure where it has come from. Any help will be much appreciated. :)
#MY CODE:
#GCSE MOCK TASK WITH GUI
import tkinter
from tkinter import *
sentence = ("Default")
window = tkinter.Tk()
window.resizable(width=FALSE, height=FALSE)
window.title("Sentence")
window.geometry("400x300")
#Add custom logo here later on
def findword():
print ("")
sentencetext = tkinter.Label(window, text="Enter Sentence: ")
sentence = tkinter.Entry(window)
sentencebutton = tkinter.Button(text="Submit")
findword = tkinter.Label(window, text="Enter Word To Find: ")
wordtofind = tkinter.Entry(window)
findwordbutton = tkinter.Button(text="Find!", command = findword)
usersentence = sentence.get()
usersentence = tkinter.Label(window,text=sentence)
shape = Canvas (bg="grey", cursor="arrow", width="400", height="8")
shape2 = Canvas (bg="grey", cursor="arrow", width="400", height="8")
#Packing & Ordering Modules
sentencetext.pack()
sentence.pack()
sentencebutton.pack()
shape.pack()
findword.pack()
wordtofind.pack()
findwordbutton.pack()
usersentence.pack()
shape2.pack()
window.mainloop()
Currently your sentence's 'submit' button doesn't actually have a command bound, and the two 'sentence' references are likely to conflict:
sentencebutton = tkinter.Button(text="Submit")
sentence = ("Default")
sentence = tkinter.Entry(window)
I can see that what you've tried to do is set it so that the variable sentence changes from "Default" to whatever one enters in the Entry window - this will not work, all you've done is set it so that sentence becomes the entry widget itself, not whatever is entered.
I would recommend creating a function called something like 'update_sentence', and rename your initial 'sentence' variable to distinguish it from the label:
var_sentence = "default"
def update_sentence:
var_sentence = sentence.get()
And then change your button so it has a command, like so:
sentencebutton = tkinter.Button(text="Submit", command = update_sentence)
Hope this helps!

Categories