Using text inputs in pygame

2019-06-23 20:20发布

问题:

import tkinter as tk    
import pygame

pygame.init()
ss = width, height = 1024, 600
screen = pygame.display.set_mode(ss)
tkinput_1 = True    

while True:

    event = pygame.event.poll()
    keys = pygame.key.get_pressed()

    if event.type == pygame.QUIT:
        pygame.quit()
        sys.exit()

    screen.fill((0,0,0))

    if tkinput_1 == True:
         tkinput_root1 = tk.Tk()
         tkinput_root1.geometry("200x200")
         tkinput_root1.title("How many teams?")
         tkinput_input1 = tk.Entry(tkinput_root1)
         tkinput_1 = False

    pygame.display.update()

tkinput_root1.mainloop()

This was just me giving the tkinter text input box a shot in pygame. I was fairly sure it wouldn't work out properly but decided I'd try it anyway cause I had nothing to lose. The tkinter screen does not show up till you've exited pygame. So, I'm not asking if anyone knows how to fix the code, but instead if anyone knows the simplest way to create a text box in pygame. I know there is a textinput class module that can be imported. If you believe that is the easiest way to do it then can you walk me through it. If not could you please let me know what you think the easiest way is. It's a small program so I want to avoid a lot of heavy lines of code for a simple text box. Let me know what you guys think. Thanks a lot in advance.

回答1:

I've tryed using Tk but the thing about using is it stops the whole pygame program when the Tk window pops up and its just not good

this is what i use Pygame InputBox its not the prettiest but it works great just download it and its really easy to use

just import inputbox

then do something like this:

inp = int(inputbox.ask(screen, 'Message')) #inp will equal whatever the input is

this is pretty much like raw_input but for pygame

its not the most aesthetically pleasing but im sure if you search around you can find maybe a nicer one



回答2:

You can use a small library i'm making, just download it and use it.

To make a simple Text box try:

from GUI import *

input_bow = InLineTextBox((0, 0), 200)  

You must give it at least a postion and the size Then in your input loop, update it :

for e in pygame.event.get():
    input_box.update(e)

and at the end, render it :

input_box.render(screen)

You can get the text with input_box.text at any moment



回答3:

I recommend using EzText. It's a great way to add text inputs into your pygame programs. I have personally used it my self and it is nice and easy and works with python 3.3.2.

http://www.pygame.org/project-EzText-920-.html



回答4:

Regarding what you said about the error with InputBox, all you have to do find and replace everywhere it says (without the quotation marks) string.join(current_string,"") with "".join(current_string), since I think this is new in python 3.4, anyway, hope that helps.